﻿using System;
using System.Diagnostics;
using System.Reflection;
using Heritage.Codebox;
using Heritage.Logging;

namespace WatcherService
{
    public class GameHandler
    {
        public static void PerformHandle() 
        {
            LogService.Debug("background", Constants.COMPONENT_BACKGROUND, "Performing background handle");
            ProcessMails();
            MakeTurns();
            SendMails();
            PutGamesOnRecord();
            StartFullGames();
        }

        private static void MakeTurns()
        {
            try
            {
                Utils.MakeTurns();
            }
            catch (Exception ex)
            {
                LogService.Error("background", Constants.COMPONENT_BACKGROUND, "Exception while handling MakeTurns: " + ex + ", " + ex.StackTrace);
                if (ex is ReflectionTypeLoadException)
                {
                    foreach (var exc in ((ReflectionTypeLoadException)ex).LoaderExceptions)
                    {
                        LogService.Error("background", Constants.COMPONENT_BACKGROUND, "LoaderException: " + exc + ", " + exc.StackTrace);
                    }
                }
            }
        }

        private static void StartFullGames()
        {
            try
            {
                Utils.StartFullGames();
            }
            catch (Exception ex)
            {
                LogService.Error("background", Constants.COMPONENT_BACKGROUND, "Exception while handling StartFullGames: " + ex.Message + ", " + ex.StackTrace);                                
            }
        }

        private static void PutGamesOnRecord()
        {
            try 
            {
                Utils.PutGamesOnRecord();
            }
            catch (Exception ex)
            {
                LogService.Error("background", Constants.COMPONENT_BACKGROUND, "Exception while handling PutGamesOnRecord: " + ex.Message + ", " + ex.StackTrace);                                
            }
        }

        private static void ProcessMails()
        {
            try 
            {
                Utils.ProcessMails();
            }
            catch (Exception ex)
            {
                LogService.Error("background", Constants.COMPONENT_BACKGROUND, "Exception while handling ProcessMails: " + ex.Message + ", " + ex.StackTrace);                                
            }
        }

        private static void SendMails()
        {
            try
            {
                Utils.SendMails();
            }
            catch (Exception ex)
            {
                LogService.Error("background", Constants.COMPONENT_BACKGROUND, "Exception while handling SendMails: " + ex.Message + ", " + ex.StackTrace);                                
            }

        }
    }
}